package com.wjd.wshow.controller;

import com.wjd.wshow.common.resource.loader.Uploader;
import com.wjd.wshow.common.resource.pojo.ThumbnailResource;
import com.wjd.wshow.service.ThumbnailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

@ResponseBody
@RequestMapping("/thumbnails")
@RestController("ThumbnailController")
public class ThumbnailController {

    private static Logger logger = LoggerFactory.getLogger(ThumbnailController.class);

    @Autowired
    private ThumbnailService thumbnailService;

    /**
     * 获取缩略图
     * @param id 缩略图id
     * @param response 响应对象
     */
    @GetMapping("/{id}")
    public final void download(@PathVariable String id, HttpServletResponse response) {
        try {
            // 获取缩略图
            ThumbnailResource thumbnail = thumbnailService.getThumbnail(id);
            if (thumbnail == null || !thumbnail.exist()) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }

            // 响应头部
            response.setHeader("Content-Type", "image/png");
            response.setHeader("Content-Length", String.format("%d", thumbnail.getSize()));

            // 输出数据流
            new Uploader().download(thumbnail, response.getOutputStream());
        } catch (Exception e) {
            logger.error(e.getCause().getMessage());
        }
    }
}
